import {Injectable, InjectionToken} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {interval, Observable} from 'rxjs';
import {take} from 'rxjs/internal/operators';

@Injectable({
  providedIn: 'root'
})
export class ServerConfigService {
  httpServer: string;
  webSocketServer: string;
  config: any;
  constructor(private http: HttpClient, private configFilePath: InjectionToken<string>) {
    this.getConfig(this.configFilePath.toString());
  }

  configObserver(): Observable<any> {
    return new Observable<any>((observe) => {
      const i = interval(10).pipe(take(300)).subscribe((num) => {
        if (this.config) {
          i.unsubscribe();
          observe.next({httpServer: this.httpServer, config: this.config, webSocketServer: this.webSocketServer});
          observe.complete();
        }
        if (num === 299) {
          throw Error('配置读取失败');
        }
      });
    });
  }


  getConfig(path) {
    /**
     * 从配置文件中读取server的信息
     * */
    this.http.get(path).subscribe((body) => {
      this.config = body;
      // const serverIp = localStorage.getItem('serverIP');
      // const serverPort = localStorage.getItem('serverPort');
      // if (serverIp !== null && serverPort !== null) {
      //   this.config.serverHost = serverIp;
      //   this.config.serverPort = serverPort;
      // }
      this.httpServer = `${this.config.httpProtocol}://${this.config.serverHost}:${this.config.serverPort}/api`;
      this.webSocketServer = `${this.config.webSocketProtocol}://${this.config.serverHost}:${this.config.serverPort}/websocket`;
    });
  }
}

export function serverConfigFactory(http: HttpClient, configFilePath: InjectionToken<string>) {
  return new ServerConfigService(http, configFilePath);
}
